package com.zx.task.manager.service.impl;

import com.zx.core.page.PageInfo;
import com.zx.core.wrapper.ListWrapper;
import com.zx.core.wrapper.PageWrapper;
import com.zx.task.manager.dao.TaskOperationsMapper;
import com.zx.task.manager.dao.TasksMapper;
import com.zx.task.manager.mapstruct.TaskOperationsMapStructMapper;
import com.zx.task.manager.model.TaskOperations;
import com.zx.task.manager.model.Tasks;
import com.zx.task.manager.param.TaskOperationsParam;
import com.zx.task.manager.service.ITaskOperationsService;
import com.zx.task.manager.vo.TaskOperationsVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * description: 任务操作记录服务实现类 <br>
 * create: 2025-10-13 20:15
 * </p>
 *
 * @author zhou  xun
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TaskOperationsServiceImpl implements ITaskOperationsService {

    private final TaskOperationsMapper taskOperationsMapper;
    private final TasksMapper tasksMapper;

    @Override
    public PageWrapper<TaskOperationsVO> getTaskOperationsVOListByPage(TaskOperationsParam taskOperationsParam) {
        PageWrapper<TaskOperationsVO> result = new PageWrapper<>();
        try {
            // 设置分页参数
            PageInfo pageInfo = new PageInfo(taskOperationsParam.getPageNum(), taskOperationsParam.getPageSize());
            taskOperationsParam.setPageNum(pageInfo.getPageNum());
            taskOperationsParam.setPageSize(pageInfo.getPageSize());

            // 查询总数
            Long count = taskOperationsMapper.countTaskOperations(taskOperationsParam.getTaskId(),
                    taskOperationsParam.getOperationType(),
                    taskOperationsParam.getOperatorName());
            if (count > 0) {
                // 分页查询列表
                List<TaskOperations> taskOperationsList = taskOperationsMapper.getTaskOperationsListByPage(taskOperationsParam.getTaskId(),
                        taskOperationsParam.getOperationType(),
                        taskOperationsParam.getOperatorName(),
                        taskOperationsParam.getPageNum(),
                        taskOperationsParam.getPageSize());
                List<TaskOperationsVO> list = taskOperationsList.stream()
                        .map(TaskOperationsMapStructMapper.INSTANCE::taskOperationsToTaskOperationsVO)
                        .toList();

                // 获取任务ID列表
                List<String> taskIds = list.stream()
                        .map(TaskOperationsVO::getTaskId)
                        .distinct()
                        .toList();

                // 批量查询任务信息
                List<Tasks> tasksList = tasksMapper.selectBatchTaskByIds(taskIds);
                Map<String, Tasks> tasksMap = tasksList.stream()
                        .collect(Collectors.toMap(Tasks::getId, tasks -> tasks));

                // 设置任务编号和任务标题
                list.forEach(taskOperationsVO -> {
                    Tasks tasks = tasksMap.get(taskOperationsVO.getTaskId());
                    if (tasks != null) {
                        taskOperationsVO.setTaskNo(tasks.getTaskNo());
                        taskOperationsVO.setTaskTitle(tasks.getTitle());
                    }
                });

                // 设置返回结果
                result.setData(list);
            }
            result.setTotal(count);
            result.setCurrentPageNum(taskOperationsParam.getPageNum());
            result.setTotalPage(pageInfo);
        } catch (Exception e) {
            log.error("分页获取任务操作记录列表时发生错误", e);
            result.fail("分页获取任务操作记录列表时发生错误: " + e.getMessage());
        }

        return result;
    }

    @Override
    public ListWrapper<TaskOperationsVO> getTaskOperationsListByTaskId(String taskId) {
        ListWrapper<TaskOperationsVO> result = new ListWrapper<>();
        try {
            // 直接根据任务ID查询所有操作记录
            List<TaskOperations> taskOperationsList = taskOperationsMapper.getTaskOperationsListByTaskId(taskId);

            // 转换为VO对象并按创建时间倒序排列（最新的在前面）
            List<TaskOperationsVO> list = taskOperationsList.stream()
                    .map(TaskOperationsMapStructMapper.INSTANCE::taskOperationsToTaskOperationsVO)
                    .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                    .collect(Collectors.toList());

            if (!list.isEmpty()) {
                // 查询任务信息
                Tasks tasks = tasksMapper.selectByPrimaryKey(taskId);
                if (tasks != null) {
                    // 设置任务编号和任务标题
                    list.forEach(taskOperationsVO -> {
                        taskOperationsVO.setTaskNo(tasks.getTaskNo());
                        taskOperationsVO.setTaskTitle(tasks.getTitle());
                    });
                }

                result.setData(list);
            }
        } catch (Exception e) {
            log.error("根据任务ID获取任务操作记录列表时发生错误", e);
            result.fail("根据任务ID获取任务操作记录列表时发生错误: " + e.getMessage());
        }
        return result;
    }

}